package tech.heptagram.staff.tools.service;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

import lombok.extern.slf4j.Slf4j;
import tech.heptagram.core.common.rest.ResponseResult;
import tech.heptagram.core.common.rest.RestResultEnum;
import tech.heptagram.staff.exception.StaffApiException;
import tech.heptagram.staff.model.BpmsProcess;
import tech.heptagram.staff.service.BpmsProcessService;

/**
 * @author wang.yuchuan
 * @createdAt 2019/3/22
 */
@Slf4j
public class BpmsProcessServiceRestTemplateImpl extends AbstractServiceImpl implements BpmsProcessService {

    private RestTemplate restTemplate;

    public BpmsProcessServiceRestTemplateImpl(String staffApiDomain, RestTemplate restTemplate) {
        super(staffApiDomain);
        this.restTemplate = restTemplate;
    }


    @Override
    public BpmsProcess findById(Integer id) {

        log.info("请求根据id获取 bpms 信息接口 findById: {}", id);

        String url = getStaffApiDomainUrl() + "/api/v3/bpms/get/" + id;

        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(url))
            .accept(MediaType.APPLICATION_JSON)
            .build();

        ParameterizedTypeReference<ResponseResult<BpmsProcess>> responseResultParameterizedTypeReference = new ParameterizedTypeReference<ResponseResult<BpmsProcess>>() {
        };
        ResponseEntity<ResponseResult<BpmsProcess>> resultEntity = restTemplate.exchange(requestEntity, responseResultParameterizedTypeReference);

        log.info("请求根据id获取 bpms 信息接口 findById 返回结果:{}", resultEntity.getBody().toString());
        if (resultEntity.getBody().getRetcode() != RestResultEnum.SUCCESS.getKey()) {
            throw new StaffApiException(resultEntity.getBody().getMsg());
        }
        return resultEntity.getBody().getData();
    }
}
